package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.enumeration.OrderType;
import com.xinzhitong.www.enumeration.PostOrderType;
import com.xinzhitong.www.exception.ConsignConditionException;
import com.xinzhitong.www.exception.ConsignException;
import com.xinzhitong.www.exception.ConsignGeneralException;
import com.xinzhitong.www.exception.consign.*;
import com.xinzhitong.www.exception.consigncondition.NoConsignEnrollException;
import com.xinzhitong.www.exception.consigngeneralexception.NoConsignGeneralException;
import com.xinzhitong.www.mapper.*;
import com.xinzhitong.www.pojo.Consign;
import com.xinzhitong.www.pojo.ConsignRequest;
import com.xinzhitong.www.pojo.User;
import com.xinzhitong.www.pojo.UserHasConsign;
import com.xinzhitong.www.service.ConsignService;
import com.xinzhitong.www.utils.FileHelper;
import com.xinzhitong.www.utils.MyPageInfo;
import com.xinzhitong.www.utils.SearchKeyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 委培服务实现
 *
 * @author 魏骆淳
 */
@Service
@Transactional
@EnableCaching
public class ConsignServiceImpl implements ConsignService {

    @Resource
    private ConsignMapper consignMapper;

    @Resource
    private TrainOrganMapper trainOrganMapper;

    @Resource
    private ClickMapper clickMapper;

    @Resource
    private TableMapper tableMapper;

    @Resource
    private SystemMessageMapper systemMessageMapper;

    @Resource
    private PostMapper postMapper;

    @Override
    public Map<String, Object> getConsignInformation(Integer consignId) throws ConsignException {
        Map<String, Object> consignInformation = consignMapper.selectConsignInformation(consignId);
        List<ConsignRequest> consignRequest = consignMapper.selectConsignRequest(consignId);
        Map<String, Object> consignCount = consignMapper.selectConsignCount(consignId);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String usn = user.getUsername();
        clickMapper.insertUserClickConsign(usn,consignId);
        if (consignInformation == null || consignRequest.size() == 0 || consignCount == null) {
            throw new NullConsignInformationException();
        } else {
            Map<String, Object> companyPicture =
                    consignMapper.selectCompanyPicture((Integer) consignInformation.get("companyId"));
            if (companyPicture == null) {
                throw new NullConsignInformationException();
            } else {
                String expRequest;
                String ageRequest;
                String sexRequest;
                String consignTime =
                        consignInformation.get("startTime").toString() + "--" +
                                consignInformation.get("endTime").toString();
                //年龄要求
                if (consignInformation.get("maxAgeRequest") ==
                        null && consignInformation.get("minAgeRequest") == null) {
                    ageRequest = "没有年龄要求";
                } else if (consignInformation.get("maxAgeRequest") == null &&
                        consignInformation.get("minAgeRequest") != null) {
                    ageRequest = "大于" + consignInformation.get("minAgeRequest") + "岁";
                } else if (consignInformation.get("maxAgeRequest") != null &&
                        consignInformation.get("minAgeRequest") == null) {
                    ageRequest = "小于" + consignInformation.get("maxAgeRequest") + "岁";
                } else {
                    ageRequest = consignInformation.get("minAgeRequest") +
                            "岁到" + consignInformation.get("maxAgeRequest") + "岁";
                }
                //经验要求
                if (consignInformation.get("maxExpRequest") ==
                        null && consignInformation.get("minExpRequest") == null) {
                    expRequest = "没有经验要求";
                } else if (consignInformation.get("maxExpRequest") == null &&
                        consignInformation.get("minExpRequest") != null) {
                    expRequest = "大于" + consignInformation.get("minExpRequest") + "年";
                } else if (consignInformation.get("maxExpRequest") != null &&
                        consignInformation.get("minExpRequest") == null) {
                    expRequest = "小于" + consignInformation.get("maxExpRequest") + "年";
                } else {
                    expRequest = consignInformation.get("minExpRequest") +
                            "年到" + consignInformation.get("maxExpRequest") + "年";
                }
                //性别要求
                if ((boolean) consignInformation.get("sexRequest")) {
                    sexRequest = "男";
                } else {
                    sexRequest = "女";
                }
                List<String> consignRequests = new ArrayList<>();
                for (ConsignRequest request : consignRequest) {
                    consignRequests.add(request.getText());
                }

                Map<String, Object> map = new HashMap<>();
                Map<String, Object> mapCompanyInformation = new HashMap<>();
                Map<String, Object> mapConsignOutline = new HashMap<>();
                Map<String, Object> mapSalaryOutline = new HashMap<>();
                Map<String, Object> mapLiveAndFoodOutline = new HashMap<>();
                Map<String, Object> mapProfessionRequest = new HashMap<>();
                Map<String, Object> mapEmployRequest = new HashMap<>();
                Map<String, Object> mapCompany = new HashMap<>();
                Map<String, Object> mapCompanyOutline = new HashMap<>();

                mapCompanyInformation.put("companyPicture", FileHelper.fileURL + companyPicture.get("MIN(picture)"));
                mapCompanyInformation.put("companyName", consignInformation.get("companyName"));
                mapCompanyInformation.put("positionName", consignInformation.get("positionName"));
                mapCompanyInformation.put("requirePopulation", consignInformation.get("requirePopulation"));
                mapCompanyInformation.put("consignCount", consignCount.get("count"));

                mapConsignOutline.put("client", consignInformation.get("companyName"));
                mapConsignOutline.put("consignUnit", consignInformation.get("trainOrganName"));
                mapConsignOutline.put("consignAddress", consignInformation.get("consignAddress"));
                mapConsignOutline.put("consignTime", consignTime);
                mapConsignOutline.put("consignText", consignInformation.get("consignText"));
                mapConsignOutline.put("consignRequest", consignRequests);
                mapConsignOutline.put("consignDeadline", consignInformation.get("deadline"));
                mapConsignOutline.put("consignOtherNotice", consignInformation.get("consignOtherNotice"));

                mapSalaryOutline.put("baseSalary", consignInformation.get("baseSalary"));
                mapSalaryOutline.put("salaryDate", consignInformation.get("salaryDate"));
                mapSalaryOutline.put("payType", consignInformation.get("payType"));
                mapSalaryOutline.put("salaryOtherNotice", consignInformation.get("salaryOtherNotice"));

                mapLiveAndFoodOutline.put("liveNotice", consignInformation.get("liveNotice"));
                mapLiveAndFoodOutline.put("foodNotice", consignInformation.get("foodNotice"));
                mapLiveAndFoodOutline.put("securityNotice", consignInformation.get("securityNotice"));
                mapLiveAndFoodOutline.put("liveFoodOtherNotice", consignInformation.get("liveFoodOtherNotice"));

                mapProfessionRequest.put("jobNotice", consignInformation.get("jobText"));
                mapProfessionRequest.put("jobTimeNotice", consignInformation.get("jobTimeNotice"));
                mapProfessionRequest.put("job_way", consignInformation.get("jobWay"));
                mapProfessionRequest.put("jobOtherNotice", consignInformation.get("jobOtherNotice"));

                mapEmployRequest.put("expRequest", expRequest);
                mapEmployRequest.put("ageRequest", ageRequest);
                mapEmployRequest.put("educationBackgroundRequest", consignInformation.get("eduBackground"));
                mapEmployRequest.put("credentialRequest", consignInformation.get("credentialRequest"));
                mapEmployRequest.put("sexRequest", sexRequest);
                mapEmployRequest.put("employOtherNotice", consignInformation.get("employOtherNotice"));

                mapCompany.put("companyIntroduction", consignInformation.get("companyIntroduction"));
                mapCompany.put("companyContact", consignInformation.get("companyContact"));
                mapCompany.put("companyOutline", mapCompanyOutline);
                mapCompanyOutline.put("companyPicture", FileHelper.fileURL + companyPicture.get("MIN(picture)"));
                mapCompanyOutline.put("companyName", consignInformation.get("companyName"));
                mapCompanyOutline.put("companyStar", consignInformation.get("companyStar"));
                mapCompanyOutline.put("companyNature", consignInformation.get("companyNature"));
                mapCompanyOutline.put("companyScale", consignInformation.get("companyScale"));
                mapCompany.put("companyAddress", consignInformation.get("companyAddress"));

                map.put("companyInformation", mapCompanyInformation);
                map.put("consignOutline", mapConsignOutline);
                map.put("salaryOutline", mapSalaryOutline);
                map.put("liveAndFoodOutline", mapLiveAndFoodOutline);
                map.put("professionRequest", mapProfessionRequest);
                map.put("employRequest", mapEmployRequest);
                map.put("company", mapCompany);
                map.put("companyId", consignInformation.get("companyId"));
                return map;
            }
        }
    }

    @Override
    public void applyConsign(Integer consignId) throws ConsignException {
        Consign consignId1 = consignMapper.selectConsignId(consignId);
        if (consignId1 == null) {
            throw new NullConsignIdException();
        } else {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            UserHasConsign userHasConsign =
                    consignMapper.selectConsignApplyInformation(user.getUsername(), consignId);
            if (userHasConsign != null) {
                throw new ConsignApplyRepetitionException();
            } else {
                Map<String, Object> consignPopulation = consignMapper.selectConsignPopulation(consignId);
                if (consignPopulation.get("requirePopulation").toString().equals(
                        consignPopulation.get("count").toString()
                )) {
                    throw new FullConsignApply();
                } else {
                    Map<String, Object> consignApplyInformation = consignMapper.selectConsignOutline(consignId);
                    String url = "/consign/consignSystemMessage?id=" + consignId;
                    String title = "委培报名成功";
                    String text = "您已成功报名'" + consignApplyInformation.get("consignName") + "'";
                    consignMapper.insertConsignApplyInformation(user.getUsername(), consignId);
                    systemMessageMapper.insertSystemMessage(user.getUsername(), title, text, url);
                }
            }
        }
    }

    @Override
    public Map<String, Object> getConsignApplyInformation(Integer consignId) throws ConsignException {
        Map<String, Object> consignApplyInformation = consignMapper.selectConsignOutline(consignId);
        List<ConsignRequest> consignRequestSum = consignMapper.selectConsignRequest(consignId);
        if (consignApplyInformation == null || consignRequestSum.size() == 0) {
            throw new NullConsignApplyInformationException();
        } else {
            List<String> consignRequest = new ArrayList<>();
            for (ConsignRequest consignRequest1 : consignRequestSum) {
                if (consignRequest1.getBeChecked()) {
                    consignRequest.add(consignRequest1.getText());
                }
            }
            consignApplyInformation.put("consignRequest", consignRequest);
            return consignApplyInformation;
        }
    }

    @Override
    public Map<String, Object> getConsignTimeAndLocation(Integer consignId) throws ConsignException {
        Map<String, Object> consignLocationAndTime = consignMapper.selectConsignLocationAndTime(consignId);
        if (consignLocationAndTime == null) {
            throw new NullConsignLocationAndTimeException();
        } else {
            String consignTime = consignLocationAndTime.get("startTime") + "--" + consignLocationAndTime.get("endTime");
            consignLocationAndTime.put("consignTime", consignTime);
            consignLocationAndTime.remove("startTime");
            consignLocationAndTime.remove("endTime");
            return consignLocationAndTime;
        }
    }

    @Override
    //@Cacheable(value = "searchTest",key = "#p1 + #p2 + #p3")
    public MyPageInfo getConsignSatisfyTheConditionOf(
            Map<String, Object> conditions,
            PostOrderType consignOrderType,
            Integer pageNo,
            Integer pageSize
    ) throws ConsignException {
        String keyWord = SearchKeyUtil.makeKey("");
        String orderField = null;
        OrderType orderType = null;
        switch (consignOrderType) {
            case NEW:
                orderField = "releaseTime";
                orderType = OrderType.DESC;
                break;
            case SALARY:
                orderField = "maxSalary";
                orderType = OrderType.DESC;
                break;
        }
        conditions.put("state", "已发布");

        tableMapper.selectFieldsOfTableOrView("consign_summary");
        String[] selectFields = tableMapper.selectFieldsOfTableOrView("consign_summary");
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> consigns =
                consignMapper.selectConsignByConditions(
                        "consign_info",
                        selectFields,
                        keyWord,
                        orderField,
                        orderType,
                        conditions
                );
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(consigns);
        if (consigns.size() == 0)
            throw new NullConsignException();
        for (Map<String, Object> consign : consigns) {
            consign.put("salary", consign.get("minSalary") + "-" + consign.get("maxSalary") + "元/每月");
            consign.put("ageRequest",
                    yearDealer(
                            Integer.parseInt(consign.get("minAgeRequest").toString()),
                            Integer.parseInt(consign.get("maxAgeRequest").toString())
                    )
            );
            consign.put("consignPicture", FileHelper.fileURL + consign.get("companyPicture"));
            consign.remove("minAgeRequest");
            consign.remove("maxAgeRequest");
            consign.remove("minSalary");
            consign.remove("maxSalary");
            consign.remove("companyPicture");
        }
        return new MyPageInfo(pageInfo);
    }

    @Override
    public Map<String, Object> getConsignTime(Integer year, Integer month) throws ConsignException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> consignDayDiff = consignMapper.selectConsignDayDiff(user.getUsername());
        if (consignDayDiff == null) {
            throw new NullConsignTimeException();
        } else {
            String thisMonth, nextMonth;
            if (month <= 8) {
                thisMonth = year + "-0" + month + "-01";
                nextMonth = year + "-0" + (month + 1) + "-01";
            } else if (month == 9) {
                thisMonth = year + "-0" + month + "-01";
                nextMonth = year + "-" + (month + 1) + "-01";
            } else if (month == 12) {
                thisMonth = year + "-" + month + "-01";
                nextMonth = (year + 1) + "-01-01";
            } else if (month == 10 || month == 11) {
                thisMonth = year + "-" + month + "-01";
                nextMonth = year + "-" + (month + 1) + "-01";
            } else {
                throw new NullConsignTimeException();
            }
            List<Integer> consignDate = consignMapper.selectConsignDate(user.getUsername(), thisMonth, nextMonth);
            consignDayDiff.put("consignDate", consignDate);
            return consignDayDiff;
        }
    }

    @Override
    public Map<String, Object> getConsignSystemMessage(Integer consignId) throws ConsignException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> consignSystemMessage =
                consignMapper.selectConsignSystemMessage(user.getUsername(), consignId);
        if (consignSystemMessage == null) {
            throw new NullConsignSystemMessage();
        } else {
            consignSystemMessage.put("applyState", "报名成功");
            consignSystemMessage.put("fee", "0元");
            consignSystemMessage.put("announcements", "可在'我的课表'中查看培训时间");
            consignSystemMessage.put("question", "请拨打137-5085-0109");
            return consignSystemMessage;
        }
    }

    @Override
    public String deleteConsign(List<Integer> idList) {
        String a;
        for (Integer id : idList) {
            consignMapper.deleteConsign(id);
        }
        a = "委培删除成功";
        return a;
    }

    @Override
    public List<Map<String, Object>> getConsignCondition(Integer consignId) throws ConsignConditionException {
        List<Map<String, Object>> x = consignMapper.SelectConsignEnrollCondition(consignId);
        if (x.size() == 0)
            throw new NoConsignEnrollException();
        for (Map<String, Object> temp : x) {
            temp.replace("datetime", temp.get("datetime").toString());
        }
        return x;
    }

    @Override
    public Integer getConsignNewEnroll() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> x = consignMapper.SelectLastTime(user.getUsername());
        Date date = new Date();

        Timestamp time = new Timestamp(date.getTime());
        Timestamp lastTime = time;
        if (x != null) {
            lastTime = (Timestamp) x.get("last_login_time");
        }
        if (consignMapper.SelectNewConsign(time, user.getUsername()) == null)
            return 0;
        return consignMapper.SelectNewConsign(time, user.getUsername()).size() -
                consignMapper.SelectNewConsign(lastTime, user.getUsername()).size();
    }

    public void saveConsign(Map<String, Object> map) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        consignCache.put(user.getUsername(), map);
    }

    @Override
    public Map<String, Object> getSavedConsign() throws ConsignException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> map = consignCache.get(user.getUsername());
        if (map == null) {
            throw new NullConsignSavedException();
        } else {
            return map;
        }
    }

    @Override
    public void releaseConsign(
            Integer positionId,
            Integer requirePopulation,
            String contact,
            String address,
            double baseSalary,
            double maxSalary,
            double minSalary,
            Integer paySalaryDate,
            String payType,
            String salaryOtherNotice,
            String liveNotice,
            String foodNotice,
            String socialSecurityNotice,
            String liveFoodOtherNotice,
            String jobText,
            String jobTimeNotice,
            String jobWay,
            String jobOtherNotice,
            Boolean sexRequest,
            Integer maxAgeRequest,
            Integer minAgeRequest,
            String eduBackground,
            Integer minExpRequest,
            Integer maxExpRequest,
            String credentialRequest,
            String employOtherNotice,
            String startTime,
            String endTime,
            String deadline,
            String applyRequest,
            String otherNotice
    ) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> company = postMapper.selectCompanyByUsername(user.getUsername());
        String state = "待审核";
        Integer companyId = (Integer) company.get("companyId");
        String positionName = postMapper.selectPositionNameByPositionId(positionId);
        String postName = company.get("companyName") + "-" + positionName;
        postMapper.insertPostInformation(
                companyId,
                positionId,
                requirePopulation,
                contact,
                address,
                baseSalary,
                maxSalary,
                minSalary,
                paySalaryDate,
                payType,
                salaryOtherNotice,
                liveNotice,
                foodNotice,
                socialSecurityNotice,
                liveFoodOtherNotice,
                jobText,
                jobTimeNotice,
                jobWay,
                jobOtherNotice,
                sexRequest,
                maxAgeRequest,
                minAgeRequest,
                eduBackground,
                minExpRequest,
                maxExpRequest,
                credentialRequest,
                employOtherNotice,
                postName,
                state
        );
        Integer lastInsertId = consignMapper.selectLastInsertId();
        consignMapper.insertConsignInformation(lastInsertId, startTime, endTime, deadline, applyRequest, otherNotice);
        consignCache.clear();
    }

    @Override
    public Map<String, Object> getConsignTotalInformation(Integer consignId) throws ConsignException {
        Map<String, Object> postTotalInformation = postMapper.selectPostTotalInformation(consignId);
        Consign consign = consignMapper.selectConsign(consignId);
        if (postTotalInformation == null || consign == null) {
            throw new NullConsignIdException();
        } else {
            postTotalInformation.put("expRequest", yearDealer(
                    (Integer) postTotalInformation.get("minExpRequest"),
                    (Integer) postTotalInformation.get("maxExpRequest")
            ));
            postTotalInformation.remove("minExpRequest");
            postTotalInformation.remove("maxExpRequest");
            postTotalInformation.put("sexRequest", sexDealer((Boolean) postTotalInformation.get("sex")));
            postTotalInformation.remove("sex");
            postTotalInformation.put("startTime", consign.getStartTime());
            postTotalInformation.put("endTime", consign.getEndTime());
            postTotalInformation.put("deadline", consign.getDeadline());
            postTotalInformation.put("applyRequest", consign.getText());
            postTotalInformation.put("otherNotice", consign.getOtherNotice());
            return postTotalInformation;
        }
    }

    @Override
    public void editConsign(
            Integer consignId,
            Integer positionId,
            Integer requirePopulation,
            String contact,
            String address,
            double baseSalary,
            double maxSalary,
            double minSalary,
            Integer paySalaryDate,
            String payType,
            String salaryOtherNotice,
            String liveNotice,
            String foodNotice,
            String socialSecurityNotice,
            String liveFoodOtherNotice,
            String jobText,
            String jobTimeNotice,
            String jobWay,
            String jobOtherNotice,
            Boolean sexRequest,
            Integer maxAgeRequest,
            Integer minAgeRequest,
            String eduBackground,
            Integer minExpRequest,
            Integer maxExpRequest,
            String credentialRequest,
            String employOtherNotice,
            String startTime,
            String endTime,
            String deadline,
            String applyRequest,
            String otherNotice
    ) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> company = postMapper.selectCompanyByUsername(user.getUsername());
        String positionName = postMapper.selectPositionNameByPositionId(positionId);
        String postName = company.get("companyName") + "-" + positionName;
        postMapper.updatePost(
                consignId,
                positionId,
                requirePopulation,
                contact,
                address,
                baseSalary,
                maxSalary,
                minSalary,
                paySalaryDate,
                payType,
                salaryOtherNotice,
                liveNotice,
                foodNotice,
                socialSecurityNotice,
                liveFoodOtherNotice,
                jobText,
                jobTimeNotice,
                jobWay,
                jobOtherNotice,
                sexRequest,
                maxAgeRequest,
                minAgeRequest,
                eduBackground,
                minExpRequest,
                maxExpRequest,
                credentialRequest,
                employOtherNotice,
                postName
        );
        consignMapper.updateConsign(
                consignId,
                startTime,
                endTime,
                deadline,
                applyRequest,
                otherNotice
        );
        consignCache.clear();
    }

    @Override
    public Map<String, Object> getConsignBasicInformation(Integer consignId) throws ConsignException {
        Map<String, Object> consignInformation = consignMapper.selectConsignBasicInformation(consignId);
        if (consignInformation == null) {
            throw new NullConsignIdException();
        } else {
            return consignInformation;
        }
    }

    @Override
    public Map<String, Object> getConsignIndex(Integer consignId) throws ConsignException {
        Map<String, Object> consignIndex = consignMapper.selectConsignIndex(consignId);
        if (consignIndex == null) {
            throw new NullConsignIdException();
        } else {
            return consignIndex;
        }
    }

    /**
     * 处理年龄要求
     *
     * @param min 最小年龄
     * @param max 最大年龄
     * @return 年龄介绍字符串
     */
    private String yearDealer(Integer min, Integer max) {
        if (min == 0 && max == 0)
            return "不限";
        else if (min.equals(max))
            return min + "岁";
        else if (min > max)
            return min + "岁以上";
        else if (min.equals(0))
            return max + "岁以下";
        else
            return min + "到" + max + "岁";
    }

    @Override
    public String underConsign(Integer id) {
        Integer x = consignMapper.updateStateOfConsign(id);
        String a;
        if (x == 1)
            a = "已下架此委培";
        else
            a = "请勿重复下架";
        return a;
    }


    @Override
    public MyPageInfo getConsignGeneral(String state, String name, Integer pageNo, Integer pageSize)
            throws ConsignGeneralException {
        PageHelper.startPage(pageNo, pageSize);
        String name1 = SearchKeyUtil.makeKey(name);
        String state1 = SearchKeyUtil.makeKey(state);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Map<String, Object>> x = consignMapper.selectConsignGeneral(name1, state1, user.getUsername());
        if (x.size() == 0)
            throw new NoConsignGeneralException();

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(x);
        for (Map<String, Object> temp : pageInfo.getList()) {
            if (temp.get("publishTime") == null)
                temp.put("publishTime", null);
            else
                temp.replace("publishTime", temp.get("publishTime").toString());
        }
        return new MyPageInfo(pageInfo);
    }


    @Override
    public Map<String, Object> getRecentEditorConsign() throws ConsignException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        List<Map<String, Object>> recentEditorConsign = consignMapper.selectRecentEditorConsign(user.getUsername());
        if (recentEditorConsign.size() == 0) {
            throw new NullRecentEditorConsign();
        } else {
            for (Map<String, Object> stringObjectMap : recentEditorConsign) {
                if (stringObjectMap.get("state").equals("已发布")) {
                    stringObjectMap.put("state", String.valueOf(stringObjectMap.get("release_time")));
                }
                stringObjectMap.remove("release_time");
            }
            return recentEditorConsign.get(0);
        }
    }

    @Override
    public MyPageInfo getConsignOutline(
            Integer positionId,
            Integer pageNo,
            Integer pageSize,
            String keyWord
    ) {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("positionId", positionId);
        tableMapper.selectFieldsOfTableOrView("consign_outline_view");
        String[] selectFields = tableMapper.selectFieldsOfTableOrView("consign_outline_view");
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> consignOutline = consignMapper.selectConsignByConditions(
                "consign_outline_view",
                selectFields,
                SearchKeyUtil.makeKey(keyWord),
                "name",
                OrderType.DESC,
                conditions
        );
        for (Map<String, Object> stringObjectMap : consignOutline) {
            stringObjectMap.put("consignPicture", FileHelper.fileURL + stringObjectMap.get("picture"));
            stringObjectMap.remove("picture");
            stringObjectMap.remove("positionId");
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(consignOutline);
        return new MyPageInfo(pageInfo);
    }

    /**
    * @author 吴展鹏
    * */
    @Override
    public MyPageInfo getConsignOrganOutline(
            Integer pageNo,
            Integer pageSize,
            String state
    ){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String usn = user.getUsername();
        Integer OrganId = consignMapper.selectOrganIdByName(user.getUsername());
        List<Map<String,Object>>tryone;
        if (state.equals("")){
            tryone= consignMapper.selectAllStateConsignByOrgan(OrganId);
        }else {
            tryone = consignMapper.selectConsignByOrgan(OrganId, state);
        }
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(tryone);

        return new MyPageInfo(pageInfo);
    }

    /**
     * @author 吴展鹏
     * */
    public void updateConsignOrganConfirm(Integer consignId){
        consignMapper.ConfirmStateOfConsign(consignId);
    }

    /**
     * @author 吴展鹏
     * */
    public String updateConsignInsertOrganId(Integer consignId,Integer organId){
        consignMapper.UpdateOrganIdOfConsign(consignId,organId);

        Timestamp d = new Timestamp(System.currentTimeMillis());
        Map<String, Object> consignApplyInformation = consignMapper.selectConsignOutline(consignId);
        Map<String,Object> organApplyInformation = trainOrganMapper.selectOrganOutline(organId);
        String url = "/consign/consignSystemMessage?id=" + consignId +"&organId=" + organId;
        String title = "委培委托成功";
        String text = "'委托：" + consignApplyInformation.get("consignName") +"  委托给："+
                organApplyInformation.get("name")+ "'";
        String username = (String)organApplyInformation.get("username");

        systemMessageMapper.insertSystemMessage(username, title, text, url);
        consignMapper.UpdatePostPublishTime(d.toString(),consignId);
        return d.toString();
    }
    /**
     * 处理性别要求
     *
     * @param sex 性别要求
     * @return 性别要求
     */
    private String sexDealer(Boolean sex) {
        if (sex == null) {
            return "不限";
        } else {
            if (sex) {
                return "男";
            } else {
                return "女";
            }
        }
    }

    /**
     * 岗位缓存
     */
    private static Cache<String, Map<String, Object>> consignCache;

    static {
        //初始化缓存
        //缓存管理器
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:Consign-ehcache-setting.xml");
        consignCache = cacheManager.getCache("consignCache");
    }

}
